package com.cnzz.site1255174697.base;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;

import com.cnzz.site1255174697.R;
import com.cqyanyu.yanyu.activity.XActivity;
import com.cqyanyu.yanyu.http.XCallback;
import com.cqyanyu.yanyu.http.XResultList;
import com.cqyanyu.yanyu.http.XResultPage;
import com.cqyanyu.yanyu.utils.StatusBarUtil;
import com.cqyanyu.yanyu.view.recyclerView.YRecyclerView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

/**
 * 带下拉和上拉刷新的基本Activity
 * Created by cheng on 2016/6/16.
 */
@ContentView(R.layout.activity_base_list)
public class BaseRecyclerActivity extends XActivity implements SwipeRefreshLayout.OnRefreshListener, YRecyclerView.OnLoadMoreListener, XCallback {

    @ViewInject(R.id.mRecyclerView)
    protected YRecyclerView mRecyclerView;
    protected int page = 1;//当前页
    protected int totalPages = 0;//页总数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRecyclerView.setOnLoadMoreListener(this);
        mRecyclerView.setOnRefreshListener(this);
        StatusBarUtil.setStatusBarColor(this, R.color.white);

    }

    public void bindItemHolder(Class entityClass, Class viewholderClass) {
        mRecyclerView.bindItemHolder(entityClass, viewholderClass);
    }

    /**
     * 加载数据
     */
    public void loadData() {

    }

    @Override
    public void onRefresh() {
        page = 1;
        loadData();
    }

    @Override
    public void onLoadMore() {
        page += 1;
        loadData();
    }

    /**
     * 加载完成设置数据
     *
     * @param result
     */
    public void onSuccessSetData(Object result) {
        if (result instanceof XResultPage) {
            XResultPage xResultPage = (XResultPage) result;
            page = xResultPage.data.page;
            totalPages = xResultPage.data.totalPages;
            if (xResultPage.data.page == 1) {
                mRecyclerView.setData(xResultPage.data.data);
            } else {
                mRecyclerView.addData(xResultPage.data.data);
            }
        } else if (result instanceof XResultList) {
            XResultList xResultList = (XResultList) result;
            mRecyclerView.setData(xResultList.data);
        }
    }

    /**
     * 加载数据完成时处理
     */
    public void onFinishedEnd() {
        if (page < 2) {
            mRecyclerView.setRefreshing(false);
            mRecyclerView.setLoadMore(true);
        }
        if (page >= totalPages) {
            mRecyclerView.setLoadMore(false);
        }
        mRecyclerView.loadFinish();
    }

    @Override
    public void onSuccess(Object result) {
        onSuccessSetData(result);
    }

    @Override
    public void onFinished() {
        onFinishedEnd();
    }
}
